package com.yayo.mangement.security.service;

import com.yayo.mangement.dto.SysRoleDTO;
import com.yayo.mangement.info.UserInfo;
import com.yayo.mangement.model.SysUser;
import com.yayo.mangement.security.entity.User;
import com.yayo.mangement.service.SysRoleService;
import com.yayo.mangement.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @CustomerDetailService: 用户接口实现
 * @author: Yayo
 * @date: 2022/8/30 21:03
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findByUsername(username);
        if(sysUser == null){
            throw new RuntimeException("用户名密码错误");
        }
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(sysUser, userInfo);
        List<SysRoleDTO> list = new ArrayList<>();
        //admin为超级管理员，权限无限大
        if(Objects.equals("admin", sysUser.getUserLoginName())){

        }else {

        }

        SysRoleDTO sysRoleDTO = new SysRoleDTO();
        sysRoleDTO.setRoleName("管理员");
        list.add(sysRoleDTO);
        userInfo.setRoles(list);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userInfo, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        return new User(userInfo);
    }

}
